requirejs.config({
    baseUrl: '../js/libs',
    paths: {
        ztree:'../plugins/ztree/js/jquery.ztree.core',
        ztreeCheck:'../plugins/ztree/js/jquery.ztree.excheck.min',
        ztreeHide:'../plugins/ztree/js/jquery.ztree.exhide'
    },
    waitSeconds : 15,
	map : {
		'*' : {
			'css' : 'css'
		}
	},
    shim: { //引入没有使用requirejs模块写法的类库。backbone依赖underscore
        'ztree':['jquery'],
        'ztreeCheck':['ztree','css!../plugins/ztree/css/zTreeStyle/zTreeStyle.css'],
        'ztreeHide':['ztree']
    }
});

define([ 'jquery', 'jquery_route', 'arttemplateUtil' ,'common','config','pageJs','layer','ztree','ztreeCheck','ztreeHide'], function(
		$, jquery_route, arttemplateUtil,common,config,pageJs,layer,ztree,ztreeCheck,ztreeHide  ) {
	
	var initroleData;
	$.controller("controller.authority.role", function($model, $tplHtml, $defobj,
			$modelobj, $paramobj, $this) {
		$model($defobj);
		var param = {};
		initroleData = function($msgtype){
			common.loading();
			$defobj.data={};
			$defobj.param=param;//api/v1/role_list 等后台接口开发好后接上去 role_list_tpl.html 字段改下就行了
			common.ajax_request2('post','/api/seller/v1/role_list',param,function($data,$code,$business){
				if($code==200){
					$defobj.data=$data;
				}else{
					window.layer.msg($business.businessNote);
				}
				$('#rolelist').empty();
				App.htmlSetData('#rolelist','authority/templates/role_list_tpl.html',$defobj);
				
				if(typeof $defobj.data != 'undefined'){
					pageJs.setPage($defobj.data.pageNo,$defobj.data.totalPage,$defobj.data.totalCount,callback);
				}
				initBtn();
				layer.closeAll('loading'); //关闭加载层
			});
		}
		//分页回调
		var callback = function(page){
			param.pageNo=page;
			initroleData();
		};
		initroleData();
		//初始化事件
		$(".addRoleBtn").click(function(){
			window.location.href="#authority/role/";
		});
		var initBtn = function(){
			$(".sf-edit-btn").click(function(){
				var id = $(this).attr("data-id");
				window.location.href="#authority/role/"+id;
			});
			$(".sf-del-btn").click(function(){
				var id = $(this).attr("data-id");
				var dname = $(this).attr("data-name");
				layer.confirm('确定删除吗？', {
					  btn: ['确定','取消']
				}, function(){
					common.loading();
					var param = {role_id: id, ro_name:dname};
					common.common_ajax_request('/api/seller/v1/role_del',param,false,function(data,code,msg){
						if(code==200 && msg.businessCode==0){
							initroleData();
							layer.alert("删除成功!");
						}else{
							layer.alert("删除失败");
						}
					},"","post");
				}, function(){});
			});
		};
		
		
	});
	
	
	
	
	
	$.controller("controller.authority.role.edit", function($model, $tplHtml, $defobj,
			$modelobj, $paramobj, $this) {
		var priv_tree = null;
		/*function zTreeOnCheck(){
			var changedNodes = priv_tree.getNodes(); //获取改变的全部结点  
			var	nodes_array = priv_tree.transformToArray (changedNodes);
			for ( var i=0 ; i < nodes_array.length ; i++ ){  
			    $("#cbv_"+nodes_array[i].id).attr("checked",nodes_array[i].checked?true:false);
			}
		}*/
		var hideNodes = [];
		
		var loadTree = function(param){
			common.common_ajax_request('/api/seller/v1/priv_tree',param,false,function(data,code,msg){
				//console.debug(JSON.stringify(data));
				for(var i=0; i<data.length; i++){
					if(!data[i].display){
						data[i].isHidden = true;
						hideNodes.push({id:data[i].id, pId:data[i].pId});
					}
				}
				var setting = {check: {enable: true},data: {simpleData: {enable: true}},view: { showIcon: true, selectedMulti: true, nameIsHTML: true}};
				priv_tree=$.fn.zTree.init($("#ztreeShow"), setting, data);
				priv_tree.expandAll(true);
				layer.closeAll('loading');
			}, null, "post");
		};
		function getChildHideNodes(pId){
			var ids = [];
			for(var i=0; i<hideNodes.length; i++){
				if(hideNodes[i].pId == pId){
					ids.push(hideNodes[i].id);
				}
			}
			return ids;
		}
		function initBtn(){
			var _dataFrm = $('.right-side .roleFrm').Validform({
				tiptype:4,
				isShowRight:false,
				datatype:{
					"checkrolename": function(gets,obj,curform,regxp){
						obj.attr('errormsg','请输入1-10个字符角色名字');
						if(gets.length>0&&gets.length<=10){
							obj.attr('errormsg','您输入的角色名字已存在');
							//正确数据验证
							var flag=false;
							common.ajax_request2('post','/api/seller/v1/checkRole',{id:$('#roleId').val(),ro_name:gets},function($data,$code){
								if($code==200 && $data=='true'){
									flag=true;
								}
							},false);
							return flag;
						}
						return false;
					},
					"roidsh":function(gets,obj,curform,regxp){
						var checkedNodes = priv_tree.getCheckedNodes(true);
						//防止内容不变不验证
						$('#roidsh').val(Math.random());
						//至少选择一个权限
						if(checkedNodes.length == 0){
							return false;
						}else{
							return true;
						}
					}
				}
			});
			//保存角色操作
			$("#save_btn").click(function(){
				if(!_dataFrm.check()){
					return;
				}
				var param = {};
				var checkedNodes = priv_tree.getCheckedNodes(true);
				//至少选择一个权限
				if(checkedNodes.length == 0){
					layer.msg("至少选择一个权限!");
					return;
				}else{
					var checkIds = [];
					for(var i=0;i<checkedNodes.length;i++){
			    		checkIds.push(checkedNodes[i].id);
			    		//console.info(checkedNodes[i].isParent);
			    		if(checkedNodes[i].isParent)
			    		{
				    		var hideNodes = getChildHideNodes(checkedNodes[i].id);
				    		if(hideNodes.length > 0){
				    			checkIds.push(hideNodes);
				    		}
			    		}
					}
					param.role_ids = checkIds.join(",");
				}
				var roleId = $("#roleId").val();
				if(roleId != ''){
					param.id = roleId;
				}
				var roleName= $("#roleName").val();
				if(roleName == ''){
					layer.msg("权限名称不能为空!");
					return;
				}else{
					param.ro_name = roleName;
				}
				var roleDesc= $("#roleDesc").val();
				if(roleDesc != ''){
					param.ro_remark = roleDesc;
				}
				jQuery(this).attr('disabled','disabled');
		    	//console.info(param);
		    	common.common_ajax_request('/api/seller/v1/role_save',param,false,function(data,code,msg){
					if(code==200 && msg.businessCode==0){
		        		window.layer.alert('保存成功!', {
		      			  icon: 1,closeBtn:false
		      			}, function(){
		      				//刷新当前页面
		      				window.location.href="#authority/role";
		      			}); 
					}else{
						layer.alert(msg.businessNote);
					}
				}, "", "post"); 
			});
			//返回列表页面
			$("#ret_btn").click(function(){
				window.location.href="#authority/role";
			});
		}
		
		if($paramobj.id==''){
			$defobj.roleedithead='角色添加';
			loadTree({});
			//渲染到页面
			$model($defobj);
			initBtn();
		}else{
			$defobj.roleedithead='角色编辑';
			var param = {role_id:$paramobj.id};
			common.common_ajax_request('/api/seller/v1/get_role',param,false,function(data,code,msg){
				$defobj.roleId=data.id;
				$defobj.roleName=data.ro_name;
				$defobj.roleDesc=data.ro_remark;
				loadTree({editRoleId:param.role_id});
				//渲染到页面
				$model($defobj);
				//loadTree({ids:data.tree_ids?data.tree_ids:""});
				initBtn();
			}, null, "post");
		}
		
	});

	var App={
			name:'权限管理',
			htmlSetData:function(out_id,html_url,dataobj){
				$(out_id).html(arttemplateUtil.template.compile($.setHTML(html_url))(dataobj));
			}
	};
});